import mongoose, { Document, Schema } from 'mongoose';

export interface ITenant extends Document {
    name: string;
    code: string;
    isActive: boolean;
    createdBy: mongoose.Schema.Types.ObjectId,
    updatedBy: mongoose.Schema.Types.ObjectId,
}

const tenantSchema = new Schema<ITenant>({
    name: {
        type: String,
        required: [true, '租户名称是必填项'],
        trim: true,
        minlength: [2, '租户名称至少需要2个字符'],
        maxlength: [50, '租户名称不能超过50个字符']
    },
    isActive: {
        type: Boolean,
        default: true
    },
    code: {
        type: String,
        trim: true,
        required: [true, '租户编码是必填项'],
        minlength: [2, '租户编码至少需要2个字符'],
        maxlength: [50, '租户编码不能超过50个字符']
    },
    createdBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
    },
    updatedBy: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
    },
}, {
    timestamps: true // 自动添加 createdAt 和 updatedAt
});

// 创建索引
tenantSchema.index({ createdAt: -1 });

// 虚拟字段（不存储在数据库中）
tenantSchema.virtual('displayName').get(function () {
    return `${this.name} (${this.code})`;
});

// 实例方法
tenantSchema.methods.toJSON = function () {
    const tenant = this.toObject();
    return tenant;
};


export const TenantModel = mongoose.model<ITenant>('Tenant', tenantSchema);